package com.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.julis.R;
import com.customview.inputview.CommonUtil;


/**
 * Created by sq on 2017/4/23.
 * 封装输入控件
 */

public class InputView extends LinearLayout {
    private View mRootView;
    public static final int NORMAL = 0;
    public static final int SELECT = 1;
    public static final int RIGHT_ARROW = 2;
    public static final int ONLY_SHOW = 3;
    private String mLeftText;
    private String mHint;
    private int mMaxLines;
    private int mMode;
    private onEditClickListener mOnEditClickListener;
    private TextView mTextView;
    //    private NoEmojiEditText mEditText;
    private EditText mEditText;
    private int mBgColor;
    //    private AutoLinearLayout mLLRoot;
    private LinearLayout mLLRoot;
    private int mRightGravity;
    private int mMaxWidth;
    private View dividerLine;
    private int mLeftColor;
    private int mEditInputType;
    //    private final View mDividerLine;
    private Context mContext;
    private int mLeftDrawable;
    private onEditChangedListener mOnEditChangedListener;
    private onEditTouchListener onEditTouchListener;
    private int mLeftTvMarginLeft;
    private int mRightHeight;
    private int mLeftDrawablePadding;
    private boolean hideBottomLine = false;
    private Drawable colorVeh;

    public InputView(Context context) {
        this(context, null);
    }

    public InputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initAttrs(context, attrs);
        setOrientation(VERTICAL);
        mRootView = LayoutInflater.from(context).inflate(R.layout.layout_input_view, null);
        dividerLine = new View(context);
        dividerLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
        dividerLine.setBackgroundColor(getResources().getColor(R.color.viewcolor));
//        mDividerLine = LayoutInflater.from(context).inflate(R.layout.line_divider, null);

        initView();
    }

    public InputView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public InputView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initView() {
        addView(mRootView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        addView(dividerLine);

        mLLRoot = (LinearLayout) this.mRootView.findViewById(R.id.ll_inputview);
        mTextView = (TextView) this.mRootView.findViewById(R.id.tv_input);
//        mEditText = (NoEmojiEditText) this.mRootView.findViewById(R.id.et_input);
        mEditText = (EditText) this.mRootView.findViewById(R.id.et_input);
        mEditText.setHint(mHint);
        if (!TextUtils.isEmpty(mLeftText))
            mTextView.setText(mLeftText);
        else
            mTextView.setVisibility(GONE);


        //右边字体的高度
        if (mRightHeight != 0) {
            mEditText.setHeight(mRightHeight);
        }

        if (hideBottomLine) {
            removeView(dividerLine);
        }

        //设置左部控件的margin
        if (mLeftTvMarginLeft != 20) {//证明取的不是默认值，则进行自定义设置
            LayoutParams layLeftTv = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layLeftTv.leftMargin = mLeftTvMarginLeft;
            layLeftTv.gravity = Gravity.CENTER_VERTICAL;
            mTextView.setLayoutParams(layLeftTv);
        }
        if (mLeftDrawable != 0) {
            Drawable leftDrawable = getResources().getDrawable(mLeftDrawable);
            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
            mTextView.setCompoundDrawablePadding(CommonUtil.px2dip(getContext(), 10));
            mTextView.setCompoundDrawables(leftDrawable, null, null, null);
        }
        if (mLeftDrawablePadding != 0) {
            mTextView.setCompoundDrawablePadding(CommonUtil.px2dip(getContext(), mLeftDrawablePadding));
        }


        mTextView.setTextColor(mLeftColor);
        mEditText.setMaxLines(mMaxLines);
        mEditText.setMaxWidth(mMaxWidth);
//        mEditText.setInputType(mEditInputType);
        mLLRoot.setBackgroundColor(mBgColor);
        setMode(mMode);
        setRightGravity(mRightGravity);
//        ViewHelper.setEditTextTouchListener(this, mEditText);
        initListener();

//        setEditTextInhibitInputSpace(mEditText);
//        setEditTextInhibitInputSpeChat(mEditText);
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
//        mEditText.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (canVerticalScroll(mEditText)) {
//                    InputView.this.getParent().requestDisallowInterceptTouchEvent(true);
//                    if (event.getAction() == MotionEvent.ACTION_UP) {
//                        InputView.this.getParent().requestDisallowInterceptTouchEvent(false);
//                    }
//                }
//                return false;
//            }
//        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mOnEditChangedListener != null) {
                    mOnEditChangedListener.onAfterTextChanged(s);
                }

            }
        });
    }

    private boolean canVerticalScroll(EditText editText) {
        int scrollY = editText.getScrollY();
        int scrollRange = editText.getLayout().getHeight();
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        int scrollDifference = scrollRange - scrollExtent;
        return scrollY > 0 || scrollY < scrollDifference - 1;
    }

    /**
     * 设置右侧Edittext的Gravity
     *
     * @param mRightGravity
     */
    private void setRightGravity(int mRightGravity) {
        switch (mRightGravity) {
            case 0://left
                mEditText.setGravity(Gravity.LEFT);
                break;
            case 1:
                mEditText.setGravity(Gravity.RIGHT);
                break;
            case 2:
                mEditText.setGravity(Gravity.START);
                break;
            case 3:
                mEditText.setGravity(Gravity.END);
                break;
            case 4:
                mEditText.setGravity(Gravity.CENTER);
                break;
            case 5:
                mEditText.setGravity(Gravity.CENTER_VERTICAL | Gravity.END);
                break;
            case 6:
                mEditText.setGravity(Gravity.CENTER_HORIZONTAL);
                break;
        }
    }

    @SuppressLint("ResourceAsColor")
    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.InputView);
        if (typedArray != null) {
            mLeftText = typedArray.getString(R.styleable.InputView_leftText);
            mLeftTvMarginLeft = typedArray.getInt(R.styleable.InputView_leftTvMarginLeftMargin, 20);
            mHint = typedArray.getString(R.styleable.InputView_rightHint);
            mMode = typedArray.getInt(R.styleable.InputView_mode, NORMAL);
            mMaxLines = typedArray.getInteger(R.styleable.InputView_maxLines, 1);
            mMaxWidth = typedArray.getDimensionPixelSize(R.styleable.InputView_maxWidth, 80);
            mBgColor = typedArray.getColor(R.styleable.InputView_inputbackground, R.color.gray_ebebeb);
            mRightGravity = typedArray.getInt(R.styleable.InputView_rightGravity, 2);
            mLeftColor = typedArray.getColor(R.styleable.InputView_leftTvColor, R.color.black_333333);
            mLeftDrawable = typedArray.getResourceId(R.styleable.InputView_leftDrawable, 0);
            mRightHeight = typedArray.getInteger(R.styleable.InputView_rightHeight, 0);
            mLeftDrawablePadding = typedArray.getInteger(R.styleable.InputView_leftdrawablePadding, 0);
            hideBottomLine = typedArray.getBoolean(R.styleable.InputView_hideBottomLine, false);
//            mEditInputType = typedArray.getInt(R.styleable.InputView_editInputType, 0);
//            typedArray.recycle();
        }
    }

    public void setMode(int mode) {
        mMode = mode;
        if (mMode == SELECT) {
            mEditText.setFocusable(false);
        } else if (mMode == RIGHT_ARROW) {
            Drawable rightDrawable = mContext.getResources().getDrawable(R.mipmap.rightarrows);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            mEditText.setCompoundDrawables(null, null, rightDrawable, null);
            mEditText.setFocusable(false);
        } else if (mMode == ONLY_SHOW) {
            mEditText.setCompoundDrawables(null, null, null, null);
            mEditText.setFocusable(false);
        } else {
            mEditText.setCompoundDrawables(null, null, null, null);
        }
        mEditText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mOnEditClickListener)
                    mOnEditClickListener.onEditClick(InputView.this);
            }
        });


        mEditText.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (onEditTouchListener != null) {
                    onEditTouchListener.onEditTouch(InputView.this, event);
                }
                return false;
            }
        });
    }

    public void hideLine() {
        dividerLine.setVisibility(GONE);
    }


    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChat(EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 更详细的操作获取textView具体设置
     */
    public TextView getTextView() {
        return mTextView;
    }

    /**
     * 更详细的操作获取EditText具体设置
     */
    public EditText getEditText() {
        return mEditText;
    }

    /**
     * @return editText内容
     */
    public String getText() {
        return mEditText.getText().toString().trim();
    }

    /**
     * @return editText设置文字内容
     */
    public void setEditText(String editTextStr) {
        mEditText.setText(editTextStr);
    }

    /**
     * @return editText内容是否为空
     */
    public boolean isEmpty() {
        return TextUtils.isEmpty(mEditText.getText().toString());
    }

    /**
     * @param hint 设置edittext提示hint
     */
    public void setHint(String hint) {
        mEditText.setHint(hint);
    }

    public String getHint() {
        return mEditText.getHint().toString();
    }

    /**
     * @param hint 设置edittext提示hint 资源文件
     */
    public void setHint(@StringRes int hint) {
        mEditText.setHint(hint);
    }

    /**
     * @param leftText 设置文字
     */
    public void setLeftText(String leftText) {
        mTextView.setText(leftText);
    }

    /**
     * @param res 设置文字 资源文件
     */
    public void setLeftText(@StringRes int res) {
        mTextView.setText(res);
    }

    /**
     * @param rightText 设置文字
     */
    public void setRightText(String rightText) {
        mEditText.setText(rightText);
    }

    /**
     * @param res 设置文字 资源文件
     */
    public void setRightText(@StringRes int res) {
        mTextView.setText(res);
    }

    /**
     * 设置edittext点击监听
     *
     * @param onEditClickListener 设置文字 资源文件
     */
    public void setOnEditClickListener(onEditClickListener onEditClickListener) {
        mOnEditClickListener = onEditClickListener;
    }

    public void setEditTextStateListener(onEditChangedListener onEditChangedListener) {
        mOnEditChangedListener = onEditChangedListener;
    }


    /**
     * 设置车牌的颜色  显示具体车牌的示例
     * //接口中      0-蓝色 1-黄色 2-黑色 3-白色 4- 渐变绿色 5- 黄绿双拼色 6- 蓝白渐变色 9-不确定 11-绿色 12-红色
     * //代码数组中  0-蓝色 1-黄色 2-黑色 3-白色 4- 渐变绿色 5- 黄绿双拼色 6- 蓝白渐变色  7-绿色   8-红色
     *
     * @param carColorShow
     */
    public void setDefaultCarShow(int carColorShow) {
        switch (carColorShow) {
            case 0:
                colorVeh = mContext.getResources().getDrawable(R.drawable.blue_car);
                break;
            case 1:
                colorVeh = mContext.getResources().getDrawable(R.drawable.yellow_car);
                break;
            case 2:
                colorVeh = mContext.getResources().getDrawable(R.drawable.black_car);
                break;
            case 3:
                colorVeh = mContext.getResources().getDrawable(R.drawable.white_car);
                break;
            case 4:
                colorVeh = mContext.getResources().getDrawable(R.drawable.green_white_car);
                break;
            case 5:
                colorVeh = mContext.getResources().getDrawable(R.drawable.green_yellow_car);
                break;
            case 6:
                colorVeh = mContext.getResources().getDrawable(R.drawable.blue_white_car);
                break;
            case 7:
                colorVeh = mContext.getResources().getDrawable(R.drawable.green_car);
                break;
            case 8:
                colorVeh = mContext.getResources().getDrawable(R.drawable.red_car);
                break;
        }
        colorVeh.setBounds(0, 0, 160, 60);
        Drawable rightDrawable = mContext.getResources().getDrawable(R.mipmap.rightarrows);
        rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());

        mEditText.setPadding(250, 0, 0, 0);
        mEditText.setCompoundDrawables(colorVeh, null, rightDrawable, null);
        setEditText(getResources().getStringArray(R.array.certificate_type)[carColorShow]);
        mEditText.setWidth(300);
        mEditText.setFocusable(false);
    }

    public void setOnEditTouchListener(onEditTouchListener onEditTouchListener) {
        this.onEditTouchListener = onEditTouchListener;
    }

    /**
     * 是否使Edittext点击唤出软键盘输入
     *
     * @param showSofuInput
     */
    public void setShowSoftInput(boolean showSoftInput) {
        mEditText.setShowSoftInputOnFocus(showSoftInput);
    }

    public interface onEditTouchListener {
        void onEditTouch(View v, MotionEvent event);
    }

    public interface onEditChangedListener {
        void onAfterTextChanged(Editable s);
    }

    public interface onEditClickListener {
        void onEditClick(View view);
    }
}
